<?php
namespace App\Http\Controllers\Admin;

use Dingo\Api\Auth\Auth;
use Illuminate\Http\Request;
use App\Models\Orders;
use App\Models\Merchant;
use App\Models\MerchantOrder;
use App\Models\OrderTotals;
use App\Models\WxOrderCount;
use App\Exports\dumpExcel;
use App\Events\WeChatNoticeEvent;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class OrdercountController extends Controller
{
    protected $model;
    protected $merchant;
    protected $ordertotals;
    protected $mer_id; //商户id
    protected $duolabao;//哆啦宝费率 0.6%
    protected $pingtai;//平台费率 0.36%
    public function __construct(Orders $order, MerchantOrder $merchantOrder,OrderTotals $ordertotals)
    {
        $this->model = $order;
        $this->merchant = $merchantOrder;
        $this->ordertotals = $ordertotals;
        $this->duolabao = 0.006;//哆啦宝费率 0.6%
        $this->pingtai = 0.0036;//平台费率 0.36%
    }
    /*
    *   订单统计页面
    */
    public function count(){
        return view('admins.order.count');
    }

    /*
    *   获取商户信息
    */
    public function getmerchants(Request $request,Merchant $merchant){
        $mer_sys = auth('admin')->user(); // 商户ID
        $data = array();
        if($mer_sys->type == 1){
            $data['type'] = 1;
            $data['merchants'] = $merchant->get();
        }else{
            $data['type'] = 2;
            $merchants[0]['name'] = $mer_sys->name;
            $merchants[0]['id'] = $mer_sys->id;
            $data['merchants'] = $merchants;
        }
        return json_encode(['code' => 200, 'msg' => 'success', 'data' => $data]);
    }

    /*
    *  异步统计信息
    */
    public function countajax(Request $request,Merchant $merchant)
    {
        $begin = ""; //开始时间
        $end = ""; //结束时间
        $where = "统计条件：";//查询条件
        $manger_id = '';//商户id
        $input = $request->all();
        
        //dd($input);
        if($input){
            //获取一下商户的名称
            if($input['merchant'] == "all"){
                $where = $where."商户：所有商户；";
            }else{
                if($input['merchant'] != ''){
                    $mer_info = $merchant->where('id',$input['merchant'])->get();
                    $where  = $where. "商户：".$mer_info[0]['name'].'  ;';
                }else{
                    $where  = $where. "商户：未选择商户  ;";
                }
                
            }
            

            $mer_sys = auth('admin')->user(); // 商户ID
            if($mer_sys->type == 1){
                $manger_id = $input['merchant'];
            }else{
                $manger_id = $mer_sys->id;
            }
            //判断起始时间
            if($input['choosedate'][0] != null && $input['choosedate'][1] != null){
            //开始时间
                $begin = $input['choosedate'][0]." 00:00:00";
                $end = $input['choosedate'][1]." 23:59:59";
                $startTime = strtotime($input['choosedate'][0]);
                $endTime = strtotime($input['choosedate'][1]);
                if($startTime > $endTime){
                    dd('开始时间晚于结束时间');
                }

            }
            //记录时间条件
            $where = $where . "  日期：从 ".$input['choosedate'][0].' 到 '.$input['choosedate'][1].'  ;';
            //判断是否选择了商户
            if($input['merchant'] != ""){
                if($input['merchant'] != "all"){
                    //计算单个商户的统计信息
                   $res =  $this->computed($manger_id,$begin,$end);
                }else{
                    //计算所有商户的订单信息
                    $res =  $this->computed($manger_id,$begin,$end,true);
                }
            }
        }

        //dd($count_res);
        $data = array();
        $data['where'] = $where;
        $data['data'] = $res;
        return json_encode(['code' => 200, 'msg' => 'success', 'data' => $data]);
    }


    public function getThreeF($data){
        //保留小数点后两位有效数字
        $data = $data*100;
        $data = round($data);
        $data = $data/100;
        return  $data;
    }



    /*
    *  按商户日统计
    */

    public function daycount(Merchant $merchant){
        //获取商户openId
        $manager_openid = DB::table('manager_third_auths')->get();
        //dd($manager_openid);

        //获取全部商户
        $merchants = $merchant->get()->toArray();
        $get_mer_one = array();
        $i = 0;
        foreach($merchants as $k=>$v){
            if($v['type'] == 3){
                $get_mer_one[$i] = $v['id'];
                $i++;
            }
        }
        //按照客户设置状态再次循环
        $get_mer = array();
        $g=0;
        for($i=0;$i<count($manager_openid);$i++){
            for($j=0;$j<count($get_mer_one);$j++){
                if($manager_openid[$i]->push_type != null and $get_mer_one[$j] == $manager_openid[$i]->manager_id){
                    $set = json_decode($manager_openid[$i]->push_type);
                    //dd($set);
                    if($set->day->val == 'true'){
                        if( $get_mer_one[$j] == 57){
                            $get_mer[$g]['id'] = $get_mer_one[$j];
                            $get_mer[$g]['wx_open_id'] = $manager_openid[$i]->wx_open_id;
                            $g++;
                        }
                        
                    }
                }
            }
        }
        //统计时间区间
        $d = date("d",time());
        $d = $d -1;
        $day = date("Y-m-",time()).$d;
        $begin = $day." 00:00:01";
        $end = $day." 23:59:59";
        //dd($begin);
        //dd($end);
        //dd($get_mer);
        //循环商户列表，计算
        $sent_info = array();
        $j = 0;
        foreach($get_mer as $k=>$v){
            $sent_info[$j]['merchant'] = $v['id'];
            $sent_info[$j]['wx_open_id'] = $v['wx_open_id'];
            $res = $this->computed($v['id'],$begin,$end);
            $info = $day."日报： 您的商户下所有货机当日接单：".$res[2]['num']. "笔,其中微信: ".$res[0]['num']."笔，支付宝：".$res[1]['num']."笔; 收款共计：".$res[2]['in_count']."元，其中微信收款：".$res[0]['in_count']."元，支付宝收款： ".$res[1]['in_count']."元; 退款共计：".$res[2]['out_count']."元; 销售额：".$res[2]['total']."元;  进货成本：".$res[2]['stock_total']."元；利润（扣除支付平台费用后）：".$res[2]['profit']."元。（详情请登录计算机查看）";
            
            $sent_info[$j]['info'] = $info;
            $j++;
        }
        //dd($sent_info);
        //下面开始进行数据发送
        for($i=0;$i<count($sent_info);$i++){
            //echo $sent_info[$i]['wx_open_id'].'<br/>';
            //echo $sent_info[$i]['info'].'<br/>';
            event(new WeChatNoticeEvent($sent_info[$i]['wx_open_id'],$sent_info[$i]['info'])); //公众号推送消息
            //将数据存入数据库
            $wx_order_count = new WxOrderCount;
            $wx_order_count->manager_id = $sent_info[$i]['merchant'];
            $wx_order_count->wx_open_id = $sent_info[$i]['wx_open_id'];
            $wx_order_count->info = $sent_info[$i]['info'];
            $wx_order_count->type = 0; //0日统计1月统计
            $wx_order_count->save();
            //echo "发送成功！";
        }
    }

    /*
    *  按商户月统计
    */
    public function monthcount(Merchant $merchant){
        //获取商户openId
        $manager_openid = DB::table('manager_third_auths')->get();
        //dd($manager_openid);

        //获取全部商户
        $merchants = $merchant->get()->toArray();
        $get_mer_one = array();
        $i = 0;
        foreach($merchants as $k=>$v){
            if($v['type'] == 3){
                $get_mer_one[$i] = $v['id'];
                $i++;
            }
        }
        //按照客户设置状态再次循环
        $get_mer = array();
        $g=0;
        for($i=0;$i<count($manager_openid);$i++){
            for($j=0;$j<count($get_mer_one);$j++){
                if($manager_openid[$i]->push_type != null and $get_mer_one[$j] == $manager_openid[$i]->manager_id){
                    $set = json_decode($manager_openid[$i]->push_type);
                    //dd($set);
                    if($set->day->val == 'true'){
                        if( $get_mer_one[$j] == 57){
                            $get_mer[$g]['id'] = $get_mer_one[$j];
                            $get_mer[$g]['wx_open_id'] = $manager_openid[$i]->wx_open_id;
                            $g++;
                        }
                        
                    }
                }
            }
        }
        //统计时间区间
        $month = date("m",time());
        $month = $month -1;
        //先判断平年闰年
        $year=date("Y",time());//当前年份。
        $begin = $year.'-'.$month.'-1 00:00:01';
        if($year%100==0){//判断世纪年
            if ($year%400==0&&$year%3200!=0){
                //echo "世纪年".$year."是闰年!";//世纪年里的闰年
                if($month == 2){
                    $end = $year.'-'.$month.'-29 23:59:59';
                }elseif(in_array($month,[1,3,5,7,8,10,12])){
                    $end = $year.'-'.$month.'-31 23:59:59';
                }else{
                    $end = $year.'-'.$month.'-30 23:59:59';
                }
            }else{
                //echo "世纪年".$year."不是闰年!";
                if($month == 2){
                    $end = $year.'-'.$month.'-28 23:59:59';
                }elseif(in_array($month,[1,3,5,7,8,10,12])){
                    $end = $year.'-'.$month.'-31 23:59:59';
                }else{
                    $end = $year.'-'.$month.'-30 23:59:59';
                }
            }
        }else{
            //剩下的就是普通年了
            if($year%4==0&&$year%100!=0){
                //echo "普通年".$year."是闰年!";//普通年里的闰年
                if($month == 2){
                    $end = $year.'-'.$month.'-29 23:59:59';
                }elseif(in_array($month,[1,3,5,7,8,10,12])){
                    $end = $year.'-'.$month.'-31 23:59:59';
                }else{
                    $end = $year.'-'.$month.'-30 23:59:59';
                }
            }else{
                //echo "普通年".$year."不是闰年!";
                if($month == 2){
                    $end = $year.'-'.$month.'-28 23:59:59';
                }elseif(in_array($month,[1,3,5,7,8,10,12])){
                    $end = $year.'-'.$month.'-31 23:59:59';
                }else{
                    $end = $year.'-'.$month.'-30 23:59:59';
                }
            }
        }

        //dd($begin);
        //dd($end);
        //dd($get_mer);
        //循环商户列表，计算
        $sent_info = array();
        $j = 0;
        foreach($get_mer as $k=>$v){
            $sent_info[$j]['merchant'] = $v['id'];
            $sent_info[$j]['wx_open_id'] = $v['wx_open_id'];
           
            $res = $this->computed($v['id'],$begin,$end);
            $info = $year."年".$month."月份月报:  接单共计：".$res[2]['num']. "笔,其中微信: ".$res[0]['num']."笔，支付宝：".$res[1]['num']."笔; 收款共计：".$res[2]['in_count']."元，其中微信收款：".$res[0]['in_count']."元，支付宝收款： ".$res[1]['in_count']."元; 退款共计：".$res[2]['out_count']."元; 销售额：".$res[2]['total']."元;  进货成本：".$res[2]['stock_total']."元；利润（扣除支付平台费用后）：".$res[2]['profit']."元。（详情请登录计算机查看）";
            
            $sent_info[$j]['info'] = $info;
            $j++;
        }
        //dd($sent_info);
        //下面开始进行数据发送
        for($i=0;$i<count($sent_info);$i++){
            //echo $sent_info[$i]['wx_open_id'].'<br/>';
            //echo $sent_info[$i]['info'].'<br/>';
            event(new WeChatNoticeEvent($sent_info[$i]['wx_open_id'],$sent_info[$i]['info'])); //公众号推送消息
            //将数据存入数据库
            $wx_order_count = new WxOrderCount;
            $wx_order_count->manager_id = $sent_info[$i]['merchant'];
            $wx_order_count->wx_open_id = $sent_info[$i]['wx_open_id'];
            $wx_order_count->info = $sent_info[$i]['info'];
            $wx_order_count->type = 1; //0日统计1月统计
            $wx_order_count->save();
        }
    }



    /*
    *订单数据统计计算
    */

    public function computed($manger_id,$begin,$end,$all = false){
            $count_res = array();//计算结果
            $z_order_num = '';//总订单号
            //echo $this->mer_id ."<br/>";
            $count_in = 0;//总金额
            $count_num = 0;//订单数量
            $count_back = 0;//退款总金额
            $count_stock = 0;//总的进货成本
            $count_k_fl = 0;//总的哆啦宝扣除的费用
            $count_f_fl = 0;//总的哆啦宝退款返还的费用
            $hrc_k = 0;//hrc平台收取费用
            $hrc_f = 0;//退款后hrc平台返还的费用
            $hrc = 0;//hrc平台剩余费用

            $wechart_in_count = 0; //微信总收入
            $wechart_out_count = 0; //微信退款总数
            $wechart_num = 0;//微信订单数量
            $wechart_stock = 0;//微信进货成本
            $wechart_total = 0;//微信收入
            $wechart_total_real = 0;//微信实际收入
            $wechart_k_fl = 0;//微信支付的哆啦宝扣除的费用
            $wechart_f_fl = 0;//微信支付的哆啦宝退款返还的费用
            $wechart_hrc_k = 0;//微信hrc平台收取费用
            $wechart_hrc_f = 0;//微信退款后hrc平台返还的费用
            $wechart_hrc = 0;//微信hrc平台剩余费用

            $ali_in_count = 0; //支付宝总收入
            $ali_out_count = 0; //支付宝退款总数
            $ali_num = 0;//支付宝订单数量
            $ali_stock = 0;//支付宝进货成本
            $ali_total = 0;//支付宝收入
            $ali_total_real = 0;//支付宝实际收入
            $ali_k_fl = 0;//支付宝支付的哆啦宝扣除的费用
            $ali_f_fl = 0;//支付宝支付的哆啦宝退款返还的费用
            $ali_hrc_k = 0;//支付宝hrc平台收取费用
            $ali_hrc_f = 0;//支付宝退款后hrc平台返还的费用
            $ali_hrc = 0;//支付宝hrc平台剩余费用


            if($all){
                $data = $this->model->with('order_total')
                ->whereBetween('created_at',[$begin,$end])
                ->whereIn('order_status',[1,2,3,4]) //订单状态0待支付,1已支付待出货,2已支付已出货,3已超时,4设备故障
                ->get()
                ->toArray();
            }else{
                $data = $this->model->whereHas('order_merchant',function($query) use($manger_id) {
                    //dd($this->mer_id);
                    $query->where('merchant_id',$manger_id);
                })
                ->with('order_total')
                ->whereBetween('created_at',[$begin,$end])
                ->whereIn('order_status',[1,2,3,4]) //订单状态0待支付,1已支付待出货,2已支付已出货,3已超时,4设备故障
                ->get()
                ->toArray();
            }
            

            //dd($data);
            foreach($data as $m=>$n){
                if($n['ordersnp'] == null){
                    //总订单数量
                    $count_num += 1;
                    //计算总金额
                    $count_in += $n['order_total_price'];
                    //计算总的进货成本
                    $count_stock += $n['order_buying_price'];
                    //先算微信的支付提点
                    if($n['payment'] == 1){
                        //微信订单数量
                        $wechart_num += 1;
                        //计算微信金额
                        $wechart_in_count += $n['order_total_price'];
                        //计算微信的进货成本
                        $wechart_stock += $n['order_buying_price'];
                        $v_f = $this->getTwoF($n['order_total_price'] * $this->duolabao);//哆啦宝费率
                        $wechart_k_fl += $v_f;
                        $v_h = $this->getTwoF($n['order_total_price'] * $this->pingtai);//平台费率
                        $wechart_hrc_k += $v_h;
                    }
                    //再算支付宝的提点
                    if($n['payment'] == 2){
                        //支付宝订单数量
                        $ali_num += 1;
                        //计算支付宝金额
                        $ali_in_count += $n['order_total_price'];
                        //计算支付宝的进货成本
                        $ali_stock += $n['order_buying_price'];
                        $v_f = $this->getTwoF($n['order_total_price'] * $this->duolabao);//哆啦宝费率
                        $ali_k_fl += $v_f;
                        $v_h = $this->getTwoF($n['order_total_price'] * $this->pingtai);//平台费率
                        $ali_hrc_k += $v_h;
                    }
                    
                }else{
                    if($z_order_num != $n['ordersnp']){
                        //将总订单号保存
                        $z_order_num = $n['ordersnp'];
                        //总订单数量
                        $count_num += 1;
                        //计算总金额
                        $count_in += $n['order_total']['goods_total_amount'];
                        //计算总的进货成本
                        $count_stock += $n['order_buying_price'];
                        //先算微信的支付提点
                        if($n['payment'] == 1){
                            //微信订单数量
                            $wechart_num += 1;
                            //计算微信金额
                            $wechart_in_count += $n['order_total']['goods_total_amount'];
                            //计算微信的进货成本
                            $wechart_stock += $n['order_buying_price'];
                            $v_f = $this->getTwoF($n['order_total']['goods_total_amount'] * $this->duolabao);//哆啦宝费率
                            $wechart_k_fl += $v_f;
                            $v_h = $this->getTwoF($n['order_total']['goods_total_amount'] * $this->pingtai);//平台费率
                            $wechart_hrc_k += $v_h;
                        }
                        //再算支付宝的提点
                        if($n['payment'] == 2){
                            //支付宝订单数量
                            $ali_num += 1;
                            //计算支付宝金额
                            $ali_in_count += $n['order_total']['goods_total_amount'];
                            //计算支付宝的进货成本
                            $ali_stock += $n['order_buying_price'];
                            $v_f = $this->getTwoF($n['order_total']['goods_total_amount'] * $this->duolabao);//哆啦宝费率
                            $ali_k_fl += $v_f;
                            $v_h = $this->getTwoF($n['order_total']['goods_total_amount'] * $this->pingtai);//平台费率
                            $ali_hrc_k += $v_h;
                        }
                    }else{
                        //计算总的进货成本
                        $count_stock += $n['order_buying_price'];
                        if($n['payment'] == 1){
                            //计算微信的进货成本
                            $wechart_stock += $n['order_buying_price'];
                        }
                        if($n['payment'] == 2){
                            //计算支付宝的进货成本
                            $ali_stock += $n['order_buying_price'];
                        }
                    }
                }
            }
            //总的支付提点
            $count_k_fl = $wechart_k_fl + $ali_k_fl;
            //总的平台提点
            $hrc_k = $wechart_hrc_k + $ali_hrc_k;

            //dd($data);
            //计算订单总金额
            $count_in = $this->getTwoF($count_in);
            //计算订单进货总价
            $count_stock_total = $this->getTwoF($count_stock);

            //微信支付总额
            $wechart_in_count = $this->getTwoF($wechart_in_count);
            //微信商品进货总额
            $wechart_stock_total = $this->getTwoF($wechart_stock);

            //支付宝支付总额
            $ali_in_count = $this->getTwoF($ali_in_count);
            //微信商品进货总额
            $ali_stock_total = $this->getTwoF($ali_stock);

            
            //计算退款总额
            if($all){
                $back_data = $this->model->with('order_total')
                ->whereBetween('created_at',[$begin,$end])
                ->whereIn('order_status',[1,2,3,4]) //订单状态0待支付,1已支付待出货,2已支付已出货,3已超时,4设备故障
                ->whereIn('refund_status',[2]) //退款状态0未退款1等待退款,2退款成功
                ->get()
                ->toArray();
            }else{
                $back_data = $this->model->whereHas('order_merchant',function($query) use($manger_id) {
                    $query->where('merchant_id',$manger_id);
                })
                ->with('order_total')
                ->whereBetween('created_at',[$begin,$end])
                ->whereIn('order_status',[1,2,3,4]) //订单状态0待支付,1已支付待出货,2已支付已出货,3已超时,4设备故障
                ->whereIn('refund_status',[2]) //退款状态0未退款1等待退款,2退款成功
                ->get()
                ->toArray();
            }
            
            foreach($back_data as $m=>$n){
                    //退款总数
                    $count_back += $n['order_total_price'];
                    //先算微信的支付提点
                    if($n['payment'] == 1){
                        //计算微信退款金额
                        $wechart_out_count += $n['order_total_price'];
                        $v_f = $this->getTwoF($n['order_total_price'] * $this->duolabao);//哆啦宝费率
                        $wechart_f_fl += $v_f;
                        $v_h = $this->getTwoF($n['order_total_price'] * $this->pingtai);//平台费率
                        $wechart_hrc_f += $v_h;
                        
                    }
                    //再算支付宝的支付提点
                    if($n['payment'] == 2){
                        //计算微信退款金额
                        $ali_out_count += $n['order_total_price'];
                        $v_f = $this->getTwoF($n['order_total_price'] * $this->duolabao);//哆啦宝费率
                        $ali_f_fl += $v_f;
                        $v_h = $this->getTwoF($n['order_total_price'] * $this->pingtai);//平台费率
                        $ali_hrc_f += $v_h;
                    }
            }
            //总的支付提点
            $count_f_fl = $wechart_f_fl + $ali_f_fl;
            $hrc_f = $wechart_hrc_f + $ali_hrc_f;
            //退款总数
            $count_back = $this->getTwoF($count_back);
            //微信退款总数
            $wechart_out_count = $this->getTwoF($wechart_out_count); 
            //支付宝退款总数
            $ali_out_count =  $this->getTwoF($ali_out_count); 

            //总销售额
            $count_total = $this->getTwoF($count_in  - $count_back);
            //总的提点后金额
            $count_total_real = $this->getTwoF($count_total - $count_k_fl + $count_f_fl);

            //总利润
            $count_profit = $this->getTwoF($count_total_real - $count_stock_total);
            //平台费用
            $count_duolabao = $this->getTwoF($hrc_k - $hrc_f);


            //微信销售额
            $wechart_total = $this->getTwoF($wechart_in_count - $wechart_out_count);
            //微信实际收入
            $wechart_total_real = $this->getTwoF($wechart_total - $wechart_k_fl + $wechart_f_fl);

            //微信利润
            $wechart_profit = $this->getTwoF($wechart_total_real - $wechart_stock_total);
            //微信平台费用
            $wechart_duolabao = $this->getTwoF($wechart_hrc_k - $wechart_hrc_f);
           



            //支付宝销售额
            $ali_total = $this->getTwoF($ali_in_count - $ali_out_count);
            //支付宝实际收入
            $ali_total_real = $this->getTwoF($ali_total - $ali_k_fl + $ali_f_fl);
            //支付宝利润
            $ali_profit = $this->getTwoF($ali_total_real - $ali_stock_total);
            //支付宝平台费用
            $ali_duolabao = $this->getTwoF($ali_hrc_k - $ali_hrc_f);

            //将结果插入到数组中
            $count_res[0]['type'] = '微信';//分类
            $count_res[0]['num'] = $wechart_num; //订单总数
            $count_res[0]['in_count'] = $wechart_in_count;//已收款
            $count_res[0]['out_count'] = $wechart_out_count;//已退款
            $count_res[0]['total'] = $wechart_total;//销售额
            $count_res[0]['stock_total'] = $wechart_stock_total;//进货成本
            $count_res[0]['total_real'] = $wechart_total_real;//提点后金额
            $count_res[0]['profit'] = $wechart_profit;//利润
            $count_res[0]['duolabao'] = $wechart_duolabao;//平台费用

            $count_res[1]['type'] = '支付宝';//分类
            $count_res[1]['num'] = $ali_num; //订单总数
            $count_res[1]['in_count'] = $ali_in_count;//已收款
            $count_res[1]['out_count'] = $ali_out_count;//已退款
            $count_res[1]['total'] = $ali_total;//销售额
            $count_res[1]['stock_total'] = $ali_stock_total;//进货成本
            $count_res[1]['total_real'] = $ali_total_real;//提点后金额
            $count_res[1]['profit'] = $ali_profit;//利润
            $count_res[1]['duolabao'] = $ali_duolabao;//平台费用

            $count_res[2]['type'] = '合计';//分类
            $count_res[2]['num'] = $count_num; //订单总数
            $count_res[2]['in_count'] = $count_in;//已收款
            $count_res[2]['out_count'] = $count_back;//已退款
            $count_res[2]['total'] = $count_total;//销售额
            $count_res[2]['stock_total'] = $count_stock_total;//进货成本
            $count_res[2]['total_real'] = $count_total_real;//提点后金额
            $count_res[2]['profit'] = $count_profit;//利润
            $count_res[2]['duolabao'] = $count_duolabao;//平台费用

            return $count_res;
    }


    /*
    *保留两位有数字
    */
    public function getTwoF($data){
        //保留小数点后两位有效数字
        $data = $data*100;
        $data = round($data);
        $data = $data/100;
        return  $data;
    }

}
